package org.huangrui.juc.source.cf;

import java.util.concurrent.*;

/**
 * @Author hr
 * @Create 2024-04-01 05:31
 */
public class T05_CompletableFutureAPI {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        future();
        System.out.println(Thread.currentThread().getName() + "\t -----线程先去忙其它任务");
        System.out.println("==============================");
        future1();
    }

    private static void future1() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "\t -----come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                // 暂停几秒钟线程
                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); }

                System.out.println("----1秒后出结果:\t"+result);
                if(result > 4){
                    int i=10/0;
                }
                return result;
            },threadPool).whenComplete((v,e)->{
                if (e == null){
                    System.out.println("-----计算完成，更新系统UpdateValue："+v);
                }
            }).exceptionally((e)->{
                e.printStackTrace();
                System.out.println("异常情况："+e.getCause()+"\t"+e.getMessage());
                return null;
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPool.shutdown();
        }
        System.out.println(Thread.currentThread().getName() + "\t -----线程先去忙其它任务");
        //主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:暂停3秒钟线程
        // try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
    }

    private static void future() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t -----come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); }
            System.out.println("----1秒后出结果");
            return result;
        });
        System.out.println(Thread.currentThread().getName() + "\t -----线程先去忙其它任务");
        System.out.println(supplyAsync.get());
    }
}
